// pages/classfit/classfit.js
var common = require("../../common/common.js").common;

var leader = require("../../common/leader.js").leader;

var shoppingCar = require("../../common/shoppingCar.js");

var util = require("../../utils/util.js");

var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    piddd: "",
    refresherLoad: false,
    nextCate: 1,
    //下一级分类
    noScroll: true,
    lowerDistance: 50,
    //scroll-view触底距离
    needIsShow: false,
    //loading需要展示
    wait: true,
    //滑动切换分类是否请求，false请求，true不请求
    first_index: 0,
    //一级菜单索引
    second_index: 0,
    //二级菜单索引
    second_classfit: [],
    //二级分类
    first_classfit: [],
    //一级分类
    big_pic: true,
    num_isShow: false,
    class: [],
    //左侧分类
    style: 1,
    cate_style: 1,
    subClasses: [],
    //自分类
    choosePid: 1,
    //选中的一级分类
    chooseSubPid: 0,
    //选中的二级分类
    bottomNotice: 0,
    //到底0不显示  1显示
    page_sign: "classfit",
    cart_count: 0,
    goods: {
      sub: []
    },
    loading: 1,
    //整页加载中
    loadingSmall: 0,
    //加载商品中
    alert: 0,
    details: [],
    price: "",
    sku: "",
    buy_count: 1,
    sku_info: "",
    cart: [],
    product_id: 0,
    proId: 0,
    leader_id: "",
    color_header: "",
    color_main: "",
    color_minor: "",
    isIPX: "",
    search_con: "",
    myleaderinfo: {
      leader_id: -1,
      leader_id_true: -1
    },
    page: 1,
    tabBar: [],
    tabBar1: [{
      iconName: "icon-shouye1",
      tip: "首页",
      current: 0,
      num: 0,
      url: "/pages/index/index",
      openType: "switchTab"
    }, {
      iconName: "icon-fenlei1",
      tip: "分类",
      current: 1,
      num: 0,
      url: "/pages/classfit/classfit",
      openType: "switchTab"
    }, {
      iconName: "icon-gouwuche2",
      tip: "购物车",
      current: 0,
      num: 0,
      url: "/pages/shopcart/shopcart"
    }, {
      iconName: "icon-dingdan2",
      tip: "订单",
      current: 0,
      num: 0,
      url: "/pages/order/order",
      openType: "switchTab"
    }, {
      iconName: "icon-wode1",
      tip: "我的",
      current: 0,
      num: 0,
      url: "/pages/personal/personal",
      openType: "switchTab"
    }],
    tmplIds: [],
    //模板消息tmplIds
    subscribeMessage: true,
    vipStatus: 0,
    t_cart_num: 0,
    minimum_num: 1,
    step_num: 1,
    joinCate: 1,
    store_title: ""
  },
  onShareAppMessage: function () {
    return {
      title: this.data.store_title,
      path: "pages/classfit/classfit"
    };
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      page: 1,
      goods: [],
      class: []
    });
    this.setData({
      domain: app.globalData.domain.slice(0, -10)
    });
    wx.hideTabBar();
    var that = this;
    that.setData({
      alert_title: "提示",
      alert_post: "自定义海报请到商品详情页生成！",
      alert_stock: "库存不足，无法继续购买!",
      alert_success: "加入购物车成功",
      alert_error: "加入购物车失败",
      alert_mes1: "该商品是多属性商品，请到购物车操作",
      alert_shopcart: "购物车最多加99999个商品！",
      alert_apply_member: "你还不是会员,请先到个人中心申请吧！"
    });
    wx.hideTabBar();
    var isIPX = app.globalData.isIPX;
    var leader_id_share;
    if (options && options.my_leaderID) {
      leader_id_share = options.my_leaderID;
    }
    wx.getSystemInfo({
      success: function (res) {
        let w_height = 0;
        let isIphone = 0;
        if (res.model.search("iPhone") != -1) {
          isIphone = 1;
        }
        if (isIphone) {
          w_height = res.windowHeight;
        } else {
          w_height = res.windowHeight;
        }
        console.log(res);
        console.log(w_height * (750 / res.windowWidth));
        that.setData({
          height: w_height * (750 / res.windowWidth),
          width: res.windowWidth,
          isIPX: isIPX,
          leader_id_share: leader_id_share
        });
      }
    });
    //首次直接进入，拿openid
    if (app.globalData.user) {
      //如果直接拿到openid
      that.requestStart(app.globalData.user.openid);
    } else {
      //回调拿到openid
      app.userInfoReadyCallback = (res => {
        that.requestStart(res.openid);
      });
    }
  },
  onReachBottom: function () {
    this.getproData();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      num_isShow: false
    });
    if (wx.getStorageSync("changeUidCate")) {
      //代表，切换了城市
      this.onLoad();
      wx.removeStorage({
        key: "changeUidCate"
      });
    }
    let that = this;
    var link = app.globalData.link;
    var class_one_id, class_two_id;
    if (link && link.indexOf("classfit/classfit") != -1) {
      class_one_id = link.split("&")[0] ? link.split("&")[0].split("=")[1] : "";
      class_two_id = link.split("&")[1] ? link.split("&")[1].split("=")[1] : "";
      that.setData({
        class_one_id: class_one_id,
        class_two_id: class_two_id
      });
    }
    if (that.data.class_one_id) {
      that.setData({
        choosePid: that.data.class_one_id,
        page: 1
      });
      that.setData({
        chooseSubPid: that.data.class_two_id ? that.data.class_two_id : that.data.class_one_id
      });
      if (that.data.class_two_id) {
        that.chooseClass(that.data.class_two_id, 1, "", true);
      } else {
        that.chooseClass(that.data.class_one_id, 1, "", true);
      }
      that.data.class.forEach((item, index) => {
        if (item.id == that.data.class_one_id) {
          that.setData({
            subClasses: item.sub
          });
        }
      });
    }
    if (that.data.goods) {
      var newPro = that.changeProInfo(that.data.goods);
      var newShoppingCart = shoppingCar.getInfo();
      that.setData({
        cart_count: newShoppingCart.cart_count,
        goods: newPro
      });
    }
    setTimeout(() => {
      that.setData({
        num_isShow: true
      });
    }, 1500);
    that.getBase();
    // that.setData({
    //     page: 1,
    //     goods: []
    // });
    that.getproData();
  },
  scroll(e) {},
  preventTouchMove() {
    return;
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      num_isShow: false
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      num_isShow: false
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.requestStart();
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  scrollToUp() {
    let that = this;
    if (that.data.noScroll) {
      return;
    }
    var leader_id_true = -1;
    if (that.data.myleaderinfo.leader_id_true != -1) {
      leader_id_true = that.data.myleaderinfo.leader_id_true;
    }
    //当前二级分类所有的个数
    let second_length = that.data.second_classfit[that.data.first_index].length;
    //商品分类自动切换
    //有上一级 一级分类
    if (that.data.first_index) {
      //二级分类的第一个，下面跳转上一级分类
      if (that.data.second_index == "0") {
        let currentFirstIndex = that.data.first_index;
        that.setData({
          first_val: "first" + that.data.first_classfit[currentFirstIndex - 1].id,
          second_val: "second" + that.data.first_classfit[currentFirstIndex - 1].id,
          second_index: 0,
          first_index: currentFirstIndex - 1,
          choosePid: that.data.first_classfit[currentFirstIndex - 1].id,
          chooseSubPid: that.data.first_classfit[currentFirstIndex - 1].id,
          subClasses: that.data.second_classfit[currentFirstIndex - 1],
          refresherLoad: true
        });
        that.changeClassfitThrottle(that.data.first_classfit[that.data.first_index].id, leader_id_true, 1);
      } else {
        //还有二级分类，跳转上一个二级分类
        let currentSecondIndex = that.data.second_index;
        that.setData({
          second_val: "second" + that.data.second_classfit[that.data.first_index][currentSecondIndex - 1].id,
          second_index: currentSecondIndex - 1,
          chooseSubPid: that.data.second_classfit[that.data.first_index][currentSecondIndex - 1].id,
          refresherLoad: true
        });
        that.changeClassfitThrottle(that.data.second_classfit[that.data.first_index][that.data.second_index].id, leader_id_true, 1);
        return;
      }
    }
    that.setData({
      refresherLoad: false
    });
  },
  scrollToLower() {
    let that = this;
    that.setData({
      loadingSmall: 1
    });
    if (that.data.noScroll || that.data.loading == 1) {
      return;
    }
    var leader_id_true = -1;
    if (that.data.myleaderinfo.leader_id_true != -1) {
      leader_id_true = that.data.myleaderinfo.leader_id_true;
    }
    //当前二级分类所有的个数
    let second_length = that.data.second_classfit[that.data.first_index].length;
    //debugger;
    //商品未全部展示，走正常商品方法
    if (that.data.goods.hasOwnProperty("sub") && that.data.goods.sub.length < that.data.goodsTotal) {
      var pid = this.data.chooseSubPid;
      this.chooseClass(pid, this.data.page, "", false);
    } else {
      return;
    }
  },
  //触底切换分类节流
  changeClassfitThrottle: common.throttle(function () {
    return;
  }, 1e3),
  //页面请求开始
  requestStart: function (openid) {
    let that = this;
    common.getBottomIcon(2).then(() => {
      common.getCart();
    });
    leader.getMyLeaderInfo(openid, that.data.leader_id_share);
    //公用方法团长请求
    that.getBase(openid);
    //基础配置
    that.getClass();
    //获取左侧分类
    that.getTmplIds();
    that.getVipStatus();
  },
  //会员卡  1,2,3会员
  getVipStatus: function () {
    let that = this;
    return new Promise(function (resolve, reject) {
      common.request({
        endpoint: "vipcard/vip-verify",
        method: "POST",
        data: "",
        success: res => {
          var vipStatus = res.extra.vip_card;
          vipStatus = vipStatus == 1 || vipStatus == 2 || vipStatus == 3 ? 1 : 0;
          that.setData({
            vipStatus: vipStatus
          });
          resolve();
        },
        fail(res) {
          reject(res);
        }
      });
    });
  },
  //全局基础配置信息
  getBase: function () {
    var that = this;
    common.request({
      endpoint: "set/app_base",
      method: "get",
      data: {},
      success: res => {
        wx.setNavigationBarColor({
          frontColor: "#ffffff",
          backgroundColor: res.extra.color_main
        });
        that.setData({
          color_main: res.extra.color_main,
          color_minor: res.extra.color_minor,
          style: res.extra.style,
          sku_display: res.extra.sku_display,
          cate_style: res.extra.cate_style,
          leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
          leader_change: res.extra.l_change,
          new_member_audit: res.extra.new_member_audit,
          userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2,
          sku_num_display: res.extra.sku_num_display,
          sale_time_show: res.extra.sale_time_show,
          t_cart_num: res.extra.cart_total_num,
          store_title: res.extra.title
        });
        var features = common.getModulesSwich(res.extra.features);
        //处理数据格式
        that.setData({
          features: features
        });
      }
    });
  },
  //加载分类商品
  getClass: function () {
    var that = this;
    common.request({
      endpoint: "product/classification",
      method: "post",
      data: {
        page_type: 1
      },
      success: res => {
        that.setData({
          class: res.extra.data
        });
        let first_classfit = res.extra.data.map((item, index) => {
          return item;
        });
        let second_classfit = res.extra.data.map((item, index) => {
          return item.sub.map((i, j) => {
            return i;
          });
        });
        that.setData({
          first_classfit: first_classfit,
          second_classfit: second_classfit
        });
        //这里请求该分类的商品
        var pid = that.data.class_one_id ? that.data.class_one_id : res.extra.data[0].id;
        //优先请求链接中的一级分类>无分类
        that.setData({
          choosePid: pid
        });
        //显示二级分类
        res.extra.data.forEach((item, index) => {
          if (item.id == pid) {
            that.setData({
              subClasses: item.sub,
              chooseSubPid: that.data.class_two_id ? that.data.class_two_id : item.sub[0].id
            });
          }
        });
        that.chooseClass(that.data.chooseSubPid, 1, "", true);
      }
    });
  },
  /**
   * 选择二级分类
   */
  chooseSubClasss(e) {
    let that = this;
    that.chooseClass(e.target.dataset.id, 1, "sub");
    that.setData({
      loading: 1,
      needIsShow: true,
      chooseSubPid: e.target.dataset.id,
      second_index: e.target.dataset.index
    });
  },
  //选择分类 or 首次加载收个分类商品
  chooseClass: function (e, page, sub, needIsShow = true) {
    var that = this;
    //需要loading加载展示
    if (needIsShow) {
      that.setData({
        needIsShow: true
      });
    }
    that.setData({
      loading: 1,
      noScroll: true
    });
    //debugger
    if (e.currentTarget) {
      var pid = e.currentTarget.dataset.id;
      that.setData({
        piddd: pid,
        page: 1,
        goods: [],
        loading: 1,
        needIsShow: true,
        bottomNotice: 0,
        //不显示底部提示信息
        first_index: e.target.dataset.index,
        //一级菜单索引
        second_index: 0
      });
      that.data.class.forEach((item, index) => {
        if (item.id == pid) {
          ////debugger
          that.setData({
            choosePid: pid,
            subClasses: item.sub,
            chooseSubPid: item.sub[0].id
          });
        }
      });
    } else {
      var pid = e;
      //此处不用存subClasses，上面请求已经存了
      if (pid != that.data.chooseSubPid) {
        that.setData({
          piddd: pid,
          page: 1,
          goods: [],
          loading: 0,
          bottomNotice: 0
        });
      }
    }
    var leader_id_true = -1;
    if (that.data.myleaderinfo.leader_id_true != -1) {
      leader_id_true = that.data.myleaderinfo.leader_id_true;
    }
    var page = that.data.page;
    common.request({
      endpoint: "product/class_product",
      method: "post",
      data: {
        pid: pid,
        leader_id_true: leader_id_true,
        page: page,
        rows: 10
      },
      success: res => {
        that.setData({
          goodsTotal: res.extra.total,
          needIsShow: false,
          loading: 1
        });
        if (res.extra.sub.length > 0) {
          if (page == 1) {
            var goods = that.changeProInfo(res.extra);
          } else {
            var goodsObj = {};
            goodsObj.sub = that.data.goods.sub.concat(res.extra.sub);
            var goods = that.changeProInfo(goodsObj);
          }
          var vipStatus = that.data.vipStatus;
          goods.sub.map(x => {
            var is_vip = (vipStatus == 1 || vipStatus == 2 || vipStatus == 3) && x.is_vip == 1 ? 1 : 0;
            if (x.is_mem_level == 1) {
              if (is_vip == 1) {
                x.is_mem_level = Number(x.vip_price) > Number(x.mem_level_price) ? 1 : 0;
                x.vip_price = Number(x.vip_price) > Number(x.mem_level_price) ? x.mem_level_price : x.vip_price;
              } else {
                x.vip_price = x.mem_level_price;
              }
            }
          });
          if (goods.sub.length) {
            //规格
            goods.sub.map(item => {
              let sku_attribute = item.sku_attribute;
              var arr_sku = [];
              var arr_sku_str = [];
              let aaa = [];
              let bbb = [];
              let sell_start = item.sell_started_at;
              let sell_end = item.sell_ended_at;
              if (sell_start) {
                aaa = sell_start.split(" ");
              }
              if (sell_end) {
                bbb = sell_end.split(" ");
              }
              item.sell_started_at = aaa[0];
              item.sell_ended_at = bbb[0];
              sku_attribute.map(item => {
                var arr_sku_item = [];
                item.attribute_value.forEach((subItem, index) => {
                  arr_sku_item.push(subItem.value);
                });
                arr_sku.push(arr_sku_item);
              });
              arr_sku = that.cartesianProductOf(...arr_sku);
              arr_sku.map(item => {
                arr_sku_str.push(item.join("/"));
              });
              item.arr_sku = arr_sku;
              item.arr_sku_str = arr_sku_str;
            });
          }
          that.setData({
            goods: goods,
            loading: 0,
            page: page + 1
          });
          if (res.extra.sub.length < 10) {
            that.setData({
              bottomNotice: 1
            });
          }
        } else {
          that.setData({
            bottomNotice: 1,
            loading: 0
          });
        }
        that.setData({
          noScroll: false,
          loading: 0
        });
        if (that.data.goods.hasOwnProperty("sub") && that.data.goods.sub.length == that.data.goodsTotal) {
          //需要切换分类时，需要上拉的距离
          that.setData({});
        }
      }
    });
  },
  getproData() {
    var that = this;
    var leader_id_true = -1;
    if (that.data.myleaderinfo.leader_id_true != -1) {
      leader_id_true = that.data.myleaderinfo.leader_id_true;
    }
    var page = that.data.page;
    common.request({
      endpoint: "product/class_product",
      method: "post",
      data: {
        pid: that.data.choosePid,
        leader_id_true: leader_id_true,
        page: page,
        rows: 10
      },
      success: res => {
        that.setData({
          goodsTotal: res.extra.total,
          needIsShow: false,
          loading: 1
        });
        if (res.extra.sub.length > 0) {
          if (page == 1) {
            var goods = that.changeProInfo(res.extra);
          } else {
            var goodsObj = {};
            goodsObj.sub = that.data.goods.sub.concat(res.extra.sub);
            var goods = that.changeProInfo(goodsObj);
          }
          var vipStatus = that.data.vipStatus;
          goods.sub.map(x => {
            var is_vip = (vipStatus == 1 || vipStatus == 2 || vipStatus == 3) && x.is_vip == 1 ? 1 : 0;
            if (x.is_mem_level == 1) {
              if (is_vip == 1) {
                x.is_mem_level = Number(x.vip_price) > Number(x.mem_level_price) ? 1 : 0;
                x.vip_price = Number(x.vip_price) > Number(x.mem_level_price) ? x.mem_level_price : x.vip_price;
              } else {
                x.vip_price = x.mem_level_price;
              }
            }
          });
          if (goods.sub.length) {
            //规格
            goods.sub.map(item => {
              let sku_attribute = item.sku_attribute;
              var arr_sku = [];
              var arr_sku_str = [];
              let aaa = [];
              let bbb = [];
              let sell_start = item.sell_started_at;
              let sell_end = item.sell_ended_at;
              if (sell_start) {
                aaa = sell_start.split(" ");
              }
              if (sell_end) {
                bbb = sell_end.split(" ");
              }
              item.sell_started_at = aaa[0];
              item.sell_ended_at = bbb[0];
              sku_attribute.map(item => {
                var arr_sku_item = [];
                item.attribute_value.forEach((subItem, index) => {
                  arr_sku_item.push(subItem.value);
                });
                arr_sku.push(arr_sku_item);
              });
              arr_sku = that.cartesianProductOf(...arr_sku);
              arr_sku.map(item => {
                arr_sku_str.push(item.join("/"));
              });
              item.arr_sku = arr_sku;
              item.arr_sku_str = arr_sku_str;
            });
          }
          that.setData({
            goods: goods,
            loading: 0,
            page: page + 1
          });
          if (res.extra.sub.length < 10) {
            that.setData({
              bottomNotice: 1
            });
          }
        } else {
          that.setData({
            bottomNotice: 1,
            loading: 0
          });
        }
        that.setData({
          noScroll: false,
          loading: 0
        });
        if (that.data.goods.hasOwnProperty("sub") && that.data.goods.sub.length == that.data.goodsTotal) {
          //需要切换分类时，需要上拉的距离
          that.setData({});
        }
      }
    });
  },
  /**
   * 计算所有规格属性
   */
  cartesianProductOf() {
    return Array.prototype.reduce.call(arguments, function (a, b) {
      var ret = [];
      a.forEach(function (a) {
        b.forEach(function (b) {
          ret.push(a.concat([b]));
        });
      });
      return ret;
    }, [
      []
    ]);
  },
  close_alert: function (e) {
    this.setData({
      alert: 0
    });
  },
  //风格2购物车
  join_cart2: function (e) {
    let that = this;
    var id = e.detail.id;
    that.setData({
      joinCate: 1
    });
    e = {
      currentTarget: {
        dataset: {
          id: e.detail.id,
          single: e.detail.single,
          minimumnum: e.detail.minimumnum,
          stepnum: e.detail.stepnum
        }
      }
    };
    that.join_cart_current2(e);
  },
  //加入购物车 此处商品详情接口需要跳转，并且增加加入中的提示
  join_cart_current2(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    let single = e.currentTarget.dataset.single;
    common.request({
      // endpoint: 'product/product_info',
      endpoint: "product/shopping-push",
      method: "post",
      data: {
        id: id
      },
      success: res => {
        let details = res.extra;
        details.sku_attribute = details.sku_attribute.map(item => {
          item.attribute_value = this.selectSingleSku(item.attribute_value);
          return item;
        });
        let sku_attribute = details.sku_attribute;
        let sku = sku_attribute.reduce((s, v) => {
          s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
          return s;
        }, "");
        let sku_info = this.getProductBySku(details.sku, sku);
        let cart_count = wx.getStorageSync("cart_count");
        if (single == 1) {
          that.setData({
            minimum_num: e.currentTarget.dataset.minimumnum,
            step_num: e.currentTarget.dataset.stepnum
          });
          that.join_cart_current2_ch(details, e);
          if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
              tmplIds: that.data.tmplIds,
              success(res) {},
              fail(err) {}
            });
          }
        } else {
          that.setData({
            details: details,
            sku: sku,
            alert: 1,
            product_id: id,
            sku_info: sku_info,
            proId: id,
            buy_count: 1
          });
        }
      }
    });
  },
  join_cart_current2_ch: function (details, e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    let single = e.currentTarget.dataset.single;
    details.sku_attribute = details.sku_attribute.map(item => {
      item.attribute_value = this.selectSingleSku(item.attribute_value);
      return item;
    });
    let sku_attribute = details.sku_attribute;
    let sku = sku_attribute.reduce((s, v) => {
      s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
      return s;
    }, "");
    let sku_info = this.getProductBySku(details.sku, sku);
    if (sku_info.stock_number >= 1) {
      that.cartRequest(sku_info.item_id, "add", id, 1);
    } else {
      wx.showToast({
        title: that.data.alert_stock,
        icon: "none"
      });
    }
  },
  //购物车减
  reduceCount2(e) {
    let that = this;
    that.setData({
      joinCate: 2
    });
    var id = e.detail.id;
    let single = e.detail.single;
    if (e.detail.single == 1) {
      var params = {
        id: id
      };
      common.request({
        // endpoint: 'product/product_info',
        endpoint: "product/shopping-push",
        method: "post",
        data: params,
        success: res => {
          let details = res.extra;
          this.setData({
            commission_show: details.commission_show
          });
          details.sku_attribute = details.sku_attribute.map(item => {
            item.attribute_value = this.selectSingleSku(item.attribute_value);
            return item;
          });
          let sku_attribute = details.sku_attribute;
          let sku = sku_attribute.reduce((s, v) => {
            s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
            return s;
          }, "");
          let sku_info = this.getProductBySku(details.sku, sku);
          if (single == 1) {
            that.setData({
              minimum_num: e.detail.minimumnum,
              step_num: e.detail.stepnum
            });
            that.cartRequest(sku_info.item_id, "reduce", id, 1);
          } else {
            that.setData({
              details: details,
              sku: sku,
              alert: 1,
              product_id: id,
              sku_info: sku_info,
              proId: id,
              buy_count: 1,
              spec_fund: details.spec_fund,
              is_vip: sku_info.is_vip,
              is_mem_level: sku_info.is_mem_level,
              vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
            });
          }
        }
      });
    } else {
      wx.showToast({
        title: that.data.alert_mes1,
        icon: "none"
      });
    }
  },
  //加
  addCount2(e) {
    var that = this;
    that.setData({
      joinCate: 2
    });
    if (e.detail.item.buyCount >= e.detail.item.all_stock_num) {
      wx.showModal({
        title: that.data.alert_title,
        content: that.data.alert_stock,
        showCancel: false
      });
      return false;
    }
    e = {
      currentTarget: {
        dataset: {
          id: e.detail.id,
          single: e.detail.single,
          minimumnum: e.detail.minimumnum,
          stepnum: e.detail.stepnum
        }
      }
    };
    this.join_cart_current2(e);
  },
  join_goods2: function () {
    var that = this;
    var sku_info = that.data.sku_info;
    var buy_count = that.data.buy_count;
    var cart = wx.getStorageSync("cart") || [];
    if (sku_info.stock_number >= buy_count) {
      that.cartRequest(that.data.sku_info.item_id, "add", that.data.details.product_id, 2);
    } else {
      wx.showToast({
        title: that.data.alert_shopcart,
        icon: "none"
      });
    }
  },
  /*购物车开始*/
  join_cart: function (e) {
    var that = this;
    that.setData({
      joinCate: 1
    });
    var id = e.currentTarget.dataset.id;
    let single = e.currentTarget.dataset.single;
    common.request({
      endpoint: "product/shopping-push",
      method: "post",
      data: {
        id: id
      },
      success: res => {
        let details = res.extra;
        details.sku_attribute = details.sku_attribute.map(item => {
          item.attribute_value = this.selectSingleSku(item.attribute_value);
          return item;
        });
        let sku_attribute = details.sku_attribute;
        let sku = sku_attribute.reduce((s, v) => {
          s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
          return s;
        }, "");
        let sku_info = this.getProductBySku(details.sku, sku);
        if (single == 1) {
          that.setData({
            minimum_num: e.currentTarget.dataset.minimumnum,
            step_num: e.currentTarget.dataset.stepnum
          });
          that.join_cart_ch(details, e);
          if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
              tmplIds: that.data.tmplIds,
              success(res) {},
              fail(err) {}
            });
          }
        } else {
          that.setData({
            details: details,
            sku: sku,
            alert: 1,
            product_id: id,
            sku_info: sku_info,
            proId: id,
            buy_count: 1
          });
        }
      }
    });
  },
  //单规格购买
  join_cart_ch: function (details, e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    let single = e.currentTarget.dataset.single;
    details.sku_attribute = details.sku_attribute.map(item => {
      item.attribute_value = this.selectSingleSku(item.attribute_value);
      return item;
    });
    let sku_attribute = details.sku_attribute;
    let sku = sku_attribute.reduce((s, v) => {
      s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
      return s;
    }, "");
    let sku_info = this.getProductBySku(details.sku, sku);
    if (sku_info.stock_number >= 1) {
      that.cartRequest(sku_info.item_id, "add", id, 1);
    } else {
      wx.showToast({
        title: that.data.alert_stock,
        icon: "none"
      });
    }
  },
  cartRequest(sku, type, id, single) {
    let that = this;
    let num = 0;
    console.log(parseInt(that.data.minimum_num));
    console.log(parseInt(that.data.step_num));
    if (single == 1) {
      var addC = that.data.joinCate == 1 ? parseInt(that.data.minimum_num) : parseInt(that.data.step_num);
      num = type == "add" ? addC : -addC;
    } else {
      num = that.data.buy_count;
    }
    let goods = that.data.goods;
    let i = goods.sub.findIndex(item => item.id == id);
    if (type != "add") {
      if (goods.sub[i].cart_num <= parseInt(that.data.minimum_num)) {
        num = -goods.sub[i].cart_num;
      }
    }
    common.request({
      endpoint: "Order/cart/add",
      method: "post",
      data: {
        leader_id: that.data.myleaderinfo.leader_id != -1 ? that.data.myleaderinfo.leader_id : 0,
        sku_id: sku,
        business_id: 0,
        num: num,
        flag: 0,
        type: 0
      },
      success: res => {
        if (single == 1) {
          if (type == "add") {
            goods.sub[i].cart_num += num;
          } else {
            goods.sub[i].cart_num += num;
          }
        } else {
          goods.sub[i].cart_num += that.data.buy_count;
        }
        if (goods.sub[i].cart_num < 0) {
          goods.sub[i].cart_num = 0;
        }
        that.setData({
          goods: goods,
          alert: 0
        });
        that.getBase();
        if (that.data.subscribeMessage) {
          wx.requestSubscribeMessage({
            tmplIds: that.data.tmplIds,
            success(res) {},
            fail(err) {
              console.log(err);
            },
            complete() {}
          });
        }
      },
      fail: err => {
        wx.showModal({
          title: "提示",
          content: err.message
        });
      }
    });
  },
  /** 
   * 添加 sku 属性
   */
  addSkuAttribute: function (e) {
    let key_id = parseInt(e.currentTarget.dataset.key_id);
    let value_id = parseInt(e.currentTarget.dataset.value_id);
    let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
    let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
    let sku = this.data.sku;
    sku = this.reBlanceSku(sku, key_id, value_id);
    let attribute = this.data.details.sku_attribute;
    attribute = this.selectSku(attribute, a_key_index, a_value_index);
    let sku_info = this.getProductBySku(this.data.details.sku, sku);
    this.setData({
      sku: sku,
      ["details.sku_attribute"]: attribute,
      sku_info: sku_info
    });
  },
  /** 
   * 重平衡 sku
   * key_id: integer
   */
  reBlanceSku: function (sku, key_id, value_id) {
    let sku_lib = sku != "" ? this.splitSku(sku) : [];
    sku_lib = this.addSku(sku_lib, {
      key_id: key_id,
      value_id: value_id
    });
    sku_lib = this.sortSku(sku_lib);
    return this.buildSku(sku_lib);
  },
  /** 
   * 重建 sku
   */
  buildSku: function (sku_lib) {
    return sku_lib.map(item => {
      return item.key_id + "," + item.value_id;
    }).join("|");
  },
  /** 
   * 对选择的 sku 属性进行排序
   */
  sortSku: function (sku_lib) {
    return sku_lib.sort((pre, next) => {
      if (pre.key_id > next.key_id) {
        return 1;
      } else if (pre.key_id < next.key_id) {
        return -1;
      } else {
        return 0;
      }
    });
  },
  /** 
   * 分割现有 sku 成对象数组
   */
  splitSku: function (sku) {
    return sku.split("|").map(sku_tmp => {
      let [key, value] = sku_tmp.split(",");
      const t = {};
      t.key_id = parseInt(key);
      t.value_id = parseInt(value);
      return t;
    });
  },
  /** 
   * 添加一个 sku
   */
  addSku: function (sku_lib, sku) {
    let t = sku_lib.filter(item => {
      if (item.key_id === sku.key_id) {
        return false;
      }
      return true;
    });
    t.push(sku);
    return t;
  },
  /** 
   * 选择 sku
   */
  selectSku: function (attribues, a_index, v_index = 0) {
    if (attribues[a_index]) {
      let values = attribues[a_index].attribute_value;
      values = values.map(item => {
        item.selected = false;
        return item;
      });
      values[v_index].selected = true;
      attribues[a_index].attribute_value = values;
    }
    return attribues;
  },
  /** 
   * 选择单个 sku 属性
   */
  selectSingleSku: function (attribute_value, v_index = 0) {
    attribute_value.map(item => {
      item.selected = false;
      return item;
    });
    attribute_value[v_index].selected = true;
    return attribute_value;
  },
  save_count: function (e) {
    this.setData({
      buy_count: parseInt(e.detail.value)
    });
  },
  reduce_count: function () {
    let buy_count = this.data.buy_count;
    if (buy_count > 1) {
      buy_count--;
    }
    this.setData({
      buy_count: buy_count
    });
    common.changeIconNum(buy_count, 2);
  },
  add_count: function (e) {
    let that = this;
    that.add_count_ch(e);
    if (that.data.subscribeMessage) {
      wx.requestSubscribeMessage({
        tmplIds: that.data.tmplIds,
        success(res) {},
        fail(err) {}
      });
    }
  },
  add_count_ch: function (e) {
    let buy_count = this.data.buy_count;
    let restrictions = e.currentTarget.dataset.restrictions;
    if (restrictions == 0) {
      buy_count++;
    } else {
      if (buy_count >= restrictions) {
        wx.showModal({
          title: that.data.alert_title,
          content: "本商品限购" + restrictions + "份"
        });
      } else {
        buy_count++;
      }
    }
    this.setData({
      buy_count: buy_count
    });
    common.changeIconNum(buy_count, 2);
  },
  /**
   * 根据 sku 获取物品
   */
  getProductBySku: function (sku_products, sku) {
    return sku_products[sku];
  },
  join_goods: function () {
    let that = this;
    // that.join_goods_ch();
    that.cartRequest(that.data.sku_info.item_id, "add", that.data.details.product_id, 2);
    // if (that.data.subscribeMessage) {
    //   wx.requestSubscribeMessage({
    //     tmplIds: that.data.tmplIds,
    //     success(res) {
    //     },
    //     fail(err) {
    //     }
    //   })
    // }
  },
  // 加入购物车
  join_goods_ch: function () {
    var that = this;
    var cart_count = wx.getStorageSync("cart_count") || 0;
    var details = that.data.details;
    var sku_info = that.data.sku_info;
    var buy_count = that.data.buy_count;
    var sku_id = that.data.product_id;
    var proId = that.data.proId;
    var cart = wx.getStorageSync("cart") || [];
    cart_count = cart_count + buy_count;
    if (cart_count <= 99999) {
      if (sku_info.stock_number >= buy_count) {
        if (cart == "") {
          let goods = {
            id: sku_info.item_id,
            product_id: sku_id,
            img: details.icon_img,
            title: details.name,
            varieties: sku_info.title,
            price: sku_info.price,
            o_price: sku_info.o_price,
            count: buy_count,
            stock_number: sku_info.stock_number,
            select: 1,
            proId: proId,
            status: 1,
            spec_fund: details.spec_fund,
            is_vip: sku_info.is_vip,
            is_mem_level: sku_info.is_mem_level,
            vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
          };
          wx.showToast({
            title: that.data.alert_success,
            icon: "success",
            success: res => {
              wx.setStorage({
                key: "cart_count",
                data: cart_count
              });
              var cart = wx.getStorageSync("cart") || that.data.cart;
              cart.push(goods);
              wx.setStorage({
                key: "cart",
                data: cart
              });
              this.setData({
                cart_count: cart_count
              });
              common.changeIconNum(cart_count, 2);
              setTimeout(() => {
                let newShoppingCart = shoppingCar.getInfo();
                var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                that.setData({
                  buy_count: 1,
                  alert: 0,
                  goods: newPro
                });
              }, 500);
            }
          });
        } else {
          var total = 0;
          var index = 0;
          for (var i = 0; i < cart.length; i++) {
            if (sku_info.item_id != cart[i]["id"]) {
              total++;
            } else {
              index = i;
              break;
            }
          }
          if (total == cart.length) {
            let goods = {
              id: sku_info.item_id,
              product_id: sku_id,
              img: details.icon_img,
              title: details.name,
              varieties: sku_info.title,
              price: sku_info.price,
              o_price: sku_info.o_price,
              count: buy_count,
              stock_number: sku_info.stock_number,
              select: 1,
              proId: proId,
              status: 1
            };
            wx.showToast({
              title: that.data.alert_success,
              icon: "success",
              success: res => {
                wx.setStorage({
                  key: "cart_count",
                  data: cart_count
                });
                var cart = wx.getStorageSync("cart") || that.data.cart;
                cart.push(goods);
                wx.setStorage({
                  key: "cart",
                  data: cart
                });
                this.setData({
                  cart_count: cart_count
                });
                common.changeIconNum(cart_count, 2);
                setTimeout(() => {
                  let newShoppingCart = shoppingCar.getInfo();
                  var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                  that.setData({
                    buy_count: 1,
                    alert: 0,
                    goods: newPro
                  });
                }, 500);
              }
            });
          } else {
            cart[index]["count"] = cart[index]["count"] + buy_count;
            wx.showToast({
              title: that.data.alert_success,
              icon: "success",
              success: res => {
                wx.setStorage({
                  key: "cart_count",
                  data: cart_count
                });
                wx.setStorage({
                  key: "cart",
                  data: cart
                });
                this.setData({
                  cart_count: cart_count
                });
                common.changeIconNum(cart_count, 2);
                setTimeout(() => {
                  let newShoppingCart = shoppingCar.getInfo();
                  var newPro = that.changeProInfo(that.data.goods, newShoppingCart);
                  that.setData({
                    buy_count: 1,
                    alert: 0,
                    goods: newPro
                  });
                }, 500);
              }
            });
          }
        }
      } else {
        wx.showToast({
          title: that.data.alert_error,
          icon: "none"
        });
      }
    } else {
      wx.showToast({
        title: that.data.alert_shopcart,
        icon: "none"
      });
    }
  },
  saveWord: function (e) {
    var that = this;
    var search_con = e.detail.value;
    that.setData({
      search_con: search_con
    });
  },
  search: function () {
    var that = this;
    var search_con = that.data.search_con;
    wx.navigateTo({
      url: "/pages/search/search?search=" + search_con
    });
  },
  /**
   * 商品信息修改
   */
  changeProInfo(proInfo, carInfoParamter) {
    var cartInfo = carInfoParamter ? carInfoParamter.statisticsArry : shoppingCar.getInfo().statisticsArry;
    if (proInfo.sub.length > 0) {
      proInfo.sub.forEach((item, index) => {
        if (cartInfo.length > 0) {
          for (var i = 0; i < cartInfo.length; i++) {
            if (item.id == cartInfo[i].product_id) {
              item.buyCount = cartInfo[i].count;
              break;
            } else {
              item.buyCount = 0;
            }
          }
        } else {
          item.buyCount = 0;
        }
      });
    }
    return proInfo;
  },
  reduceCount(e) {
    let that = this;
    that.setData({
      joinCate: 2
    });
    //不是会员
    if (that.data.vipStatus <= 0) {
      if (e.detail.onlyvip == 1) {
        wx.showModal({
          title: "提示",
          content: "该商品仅限会员购买，请先成为会员",
          confirmText: "去升级",
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: "/memberVip/pages/memberAuthor/memberAuthor"
              });
              return;
            } else {
              return;
            }
          }
        });
        return;
      }
    }
    var id = e.currentTarget.dataset.id;
    let single = e.currentTarget.dataset.single;
    console.log(e);
    if (e.currentTarget.dataset.single == 1) {
      var params = {
        id: id
      };
      common.request({
        // endpoint: 'product/product_info',
        endpoint: "product/shopping-push",
        method: "post",
        data: params,
        success: res => {
          let details = res.extra;
          this.setData({
            commission_show: details.commission_show
          });
          details.sku_attribute = details.sku_attribute.map(item => {
            item.attribute_value = this.selectSingleSku(item.attribute_value);
            return item;
          });
          let sku_attribute = details.sku_attribute;
          let sku = sku_attribute.reduce((s, v) => {
            s = this.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
            return s;
          }, "");
          let sku_info = this.getProductBySku(details.sku, sku);
          if (single == 1) {
            that.setData({
              minimum_num: e.currentTarget.dataset.minimumnum,
              step_num: e.currentTarget.dataset.stepnum
            });
            that.cartRequest(sku_info.item_id, "reduce", id, 1);
          } else {
            that.setData({
              details: details,
              sku: sku,
              alert: 1,
              product_id: id,
              sku_info: sku_info,
              proId: id,
              buy_count: 1,
              spec_fund: details.spec_fund,
              is_vip: sku_info.is_vip,
              is_mem_level: sku_info.is_mem_level,
              vip_price: Number(sku_info.vip_price) > Number(sku_info.mem_level_price) ? sku_info.mem_level_price : sku_info.vip_price
            });
          }
        }
      });
    } else {
      wx.showToast({
        title: that.data.alert_mes1,
        icon: "none"
      });
    }
  },
  addCount(e) {
    let that = this;
    that.setData({
      joinCate: 2
    });
    this.join_cart_current2(e);
    // that.join_cart(e)
  },
  //获取tmplIds
  getTmplIds: function () {
    let that = this;
    const version = wx.getSystemInfoSync().SDKVersion;
    if (util.compareVersion(version, "2.8.2") < 0) {
      that.setData({
        tmplIds: [],
        subscribeMessage: false
      });
      return;
    }
    common.request({
      endpoint: "set/template_get",
      method: "post",
      data: {},
      header: {
        "content-type": "application/json"
      },
      success: res => {
        let tmplIds = [];
        let subscribeMessage = true;
        res.extra.map(v => {
          if ((v.type == "21" || v.type == "22" || v.type == "23") && v.status == "1") {
            tmplIds.push(v.template_id);
          }
        });
        if (!tmplIds.length) {
          subscribeMessage = false;
        }
        that.setData({
          tmplIds: tmplIds,
          subscribeMessage: subscribeMessage
        });
      }
    });
  },
  goToDetail: function (e) {
    let that = this;
    if (that.data.userAuditStatus != 2 && this.data.new_member_audit == 1) {
      wx.showModal({
        title: that.data.alert_title,
        content: that.data.alert_apply_member,
        showCancel: false
      });
      return false;
    }
    wx.navigateTo({
      url: e.currentTarget.dataset.url
    });
  },
  /**
   * 改变购物车上标数字
   */
  changeIconNum(num, index) {
    let that = this;
    var tabBar = that.data.tabBar;
    tabBar[index].num = num;
    that.setData({
      tabBar: tabBar
    });
  }
});